  	package com.ds.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ds.dao.CUserDAO;
import com.ds.dao.CompanyInfoDAO;
import com.ds.dao.PhoneCodeDAO;
import com.ds.entity.CUserEntity;
import com.ds.entity.DSResult;
import com.ds.entity.EvaluationArchive;
import com.ds.entity.PhoneCodeEntity;
import com.ds.utils.GlobalConfig;
import com.ds.utils.HttpClient;
import com.ds.utils.SMSSendUtis;
import com.ds.utils.SequenceUtils;
import com.ds.utils.WxUtils;


@RestController
@Api(value = "用户接口", tags = { "用户接口" })
@RequestMapping("api")
public class CUserController {
	
	private static Logger logger = LoggerFactory.getLogger(CUserController.class);
	
	@Autowired
	CUserDAO dsCUserDAO; 
	
	@Autowired
	PhoneCodeDAO phoneCodeDAO ; 
	
	@ApiOperation(value = "根据code获取用户信息")
	@PostMapping("/login")
	public DSResult<CUserEntity> get(HttpServletRequest request, String code){
		try {
			if(code!=null){
				String wxInfo = HttpClient.sendGetRequest(GlobalConfig.url+"userinfo?usercode="+code, null,new  HttpHeaders());
				JSONObject wxMap = JSON.parseObject(wxInfo);
				String openId = wxMap.getString("openId");
				logger.info(wxMap.toJSONString());
				if(openId==null){return new DSResult<CUserEntity>("获取微信信息失败",false); }
				CUserEntity tmp = new CUserEntity();
				tmp.setWxid(openId);
				tmp.setUnStatus("2");
				List< CUserEntity > d = dsCUserDAO.selectDsCUserList(tmp);
				if(d==null||d.size()==0){
					tmp.setWxImg(wxMap.getString("headImgUrl"));
					tmp.setUserName(wxMap.getString("nickName"));
					logger.info("not binded, return is {} by code: {}", tmp, code);
					return new DSResult<CUserEntity>("未绑定",false,tmp);
				}
				CUserEntity user = d.get(0);
				if(user.getStatus().equals("0")){
					return new DSResult<CUserEntity>("审核中",true,user);
				}
				logger.info("get user {} by code: {}", user, code);
				request.getSession().setAttribute("user", user);
				request.getSession().setAttribute("openId", openId);
				return  new DSResult<CUserEntity>("存在用户", true, user);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new DSResult<CUserEntity>("登录失败",false); 
		}
		return  new DSResult<CUserEntity>("无用户信息",false);
	}
	
	@ApiOperation(value = "企业用户注册")
	@PostMapping("/register")
	public DSResult<CUserEntity> register(CUserEntity cUserEntity){
		try {
			CUserEntity tmp = new CUserEntity();
			tmp.setCompanyId(cUserEntity.getCompanyId());
			tmp.setUserType("1");
			tmp.setStatus("1");
			List< CUserEntity > data = dsCUserDAO.selectDsCUserList(tmp);
			if(data!=null&&data.size()>0){
				return  new DSResult<CUserEntity>("已注册",false,data.get(0));
			}
			tmp.setStatus("0");
			data = dsCUserDAO.selectDsCUserList(tmp);
			if(data!=null&&data.size()>0){
				return  new DSResult<CUserEntity>("审核中",false,data.get(0));
			}
			//获取微信头像？
			cUserEntity.setStatus("0");
			cUserEntity.setUserType("1");
			cUserEntity.setCreateTime(new Date());
			dsCUserDAO.insertDsCUser(cUserEntity);
			return  new DSResult<CUserEntity>(cUserEntity);
		} catch (Exception e) {
			e.printStackTrace();
			return  new DSResult<CUserEntity>("系统出错",false);
		}
	}
	
	@ApiOperation(value = "生成链接")
	@PostMapping("/createUrl")
	public DSResult<String> createUrl(HttpServletRequest request,Long id){
		CUserEntity cUserEntity = new  CUserEntity();
		try {
			CUserEntity test =(CUserEntity) request.getSession().getAttribute("user");
			logger.info("session info {}",test);
			CUserEntity user = dsCUserDAO.selectDsCUserById(id);
			if(user!=null){
				cUserEntity.setCompanyId(user.getCompanyId());
				cUserEntity.setCompanyName(user.getCompanyName());
				cUserEntity.setCompanyType(user.getCompanyType());
			}
			cUserEntity.setStatus("0");
			cUserEntity.setUserType("0");
			cUserEntity.setCreateTime(new Date());
			cUserEntity.setRegisterNumber(SequenceUtils.getRandomString("", 6));
			dsCUserDAO.insertDsCUser(cUserEntity);
			return  new DSResult<String>(cUserEntity.getRegisterNumber());
		} catch (Exception e) {
			e.printStackTrace();
			return  new DSResult<String>("系统出错",false);
		}
	}
	
	@ApiOperation(value = "添加人员")
	@PostMapping("/add")
	public DSResult<String> add(@ApiParam("生成url带的code")String urlCode,
			@ApiParam("微信code")String code,CUserEntity cUserEntity){
		try {
			CUserEntity tmp = new CUserEntity();
			tmp.setRegisterNumber(urlCode);
			tmp.setStatus("0");
			tmp.setUserType("0");
			List< CUserEntity > data = dsCUserDAO.selectDsCUserList(tmp);
			if(data==null||data.size()==0){return  new DSResult<String>("无需激活用户",false);}
			CUserEntity d = data.get(0);
			String wxInfo = HttpClient.sendGetRequest(GlobalConfig.url+"userinfo?usercode="+code, null,new  HttpHeaders());
			JSONObject wxMap = JSON.parseObject(wxInfo);
			String openId = wxMap.getString("openId");
			//头像
			d.setUserName(cUserEntity.getUserName());
			d.setUserPhone(cUserEntity.getUserPhone());
			d.setCompanyPosition(cUserEntity.getCompanyPosition());
			d.setWxid(openId);
			d.setStatus("1");
			d.setWxImg(wxMap.getString("headImgUrl"));
			//d.setUserName(wxMap.getString("nickName"));
			dsCUserDAO.updateDsCUserById(d);
			return  new DSResult<String>();
		} catch (Exception e) {
			e.printStackTrace();
			return  new DSResult<String>("系统出错",false);
		}
	}
	
	@ApiOperation(value = "更新")
	@PostMapping("/update")
	public DSResult<String> update(CUserEntity cUserEntity){
		try {
			CUserEntity tmp = new CUserEntity();
			tmp.setId(cUserEntity.getId());
			tmp.setUserPhone(cUserEntity.getUserPhone());
			tmp.setCompanyPosition(cUserEntity.getCompanyPosition());
			dsCUserDAO.updateDsCUserById(tmp);
			return  new DSResult<String>();
		} catch (Exception e) {
			e.printStackTrace();
			return  new DSResult<String>("系统出错",false);
		}
	}
	
	@ApiOperation(value = "更新")
	@PostMapping("/delete")
	public DSResult<String> delete(Long id){
		try {
			//dsCUserDAO.deleteById(id);
			return  new DSResult<String>();
		} catch (Exception e) {
			e.printStackTrace();
			return  new DSResult<String>("系统出错",false);
		}
	}
	
	@ApiOperation(value = "获取企业人员信息")
	@PostMapping("/list")
	public DSResult<List<CUserEntity>> register(String wxid){
		try {
			CUserEntity tmp = new CUserEntity();
			tmp.setWxid(wxid);
			tmp.setUserType("1");
			tmp.setStatus("1");
			List< CUserEntity > data = dsCUserDAO.selectDsCUserList(tmp);
			if(data==null||data.size()==0){return  new DSResult<List<CUserEntity>>("无用户信息",false);}
			CUserEntity d = data.get(0);
			CUserEntity tmp2 = new CUserEntity();
			tmp2.setUserType("0");
			tmp2.setStatus("1");
			tmp2.setCompanyId(d.getCompanyId());
			List< CUserEntity > data2 = dsCUserDAO.selectDsCUserList(tmp2);
			return  new DSResult<List<CUserEntity>>(data2);
		} catch (Exception e) {
			e.printStackTrace();
			return  new DSResult<List<CUserEntity>>("系统出错",false);
		}
		
	}
	
	@ApiOperation(value = "发送手机验证码")
	@PostMapping("/sendCode")
	public DSResult<String> sendCode(String phone){
		try {
			String code = SequenceUtils.getRandomNum("", 6);
			//发送手机号
			//存库
			SMSSendUtis.send(code,phone);
			PhoneCodeEntity pce = new PhoneCodeEntity();
			pce.setCode(code);
			pce.setPhone(phone);
			pce.setCreateTime(new Date());
			pce.setStatus(0L);
			phoneCodeDAO.insertDsPhoneCode(pce);
			return  new DSResult<String>(code);
		} catch (Exception e) {
			e.printStackTrace();
			return  new DSResult<String>("系统出错",false);
		}
		
	}
	
	@ApiOperation(value = "校验验证码")
	@PostMapping("/ckeckCode")
	public DSResult<String> ckeckCode(String phone,String authCode){
		try {
			PhoneCodeEntity pce = new PhoneCodeEntity();
			pce.setCode(authCode);
			pce.setPhone(phone);
			pce.setStatus(0L);
			List< PhoneCodeEntity > data = phoneCodeDAO.selectDsPhoneCodeList(pce);
			if(data==null||data.size()==0){return  new DSResult<String>("验证码错误",false);}
			
			PhoneCodeEntity d = data.get(0);
			long t = d.getCreateTime().getTime();
			long now = new Date().getTime();
			if(now-t>(GlobalConfig.min15)){return  new DSResult<String>("验证码过期",false);}
			d.setStatus(1L);
			phoneCodeDAO.updateDsPhoneCodeById(d);
			return  new DSResult<String>();
		} catch (Exception e) {
			e.printStackTrace();
			return  new DSResult<String>("系统出错",false);
		}
	}
	
	@ApiOperation(value = "获取签名")
	@PostMapping("/getSignature")
	public DSResult<JSONObject> getSignature(String url){
		JSONObject obj = WxUtils.getSignature(url);
		return  new DSResult<JSONObject>(obj);
	}

}
